package com.lalilu.lread.utils

import android.net.Uri
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.io.FileUtils
import java.io.File


object FileUtil {

    suspend fun saveFile(path: String, data: ByteArray?): Uri? = withContext(Dispatchers.IO) {
        if (data == null || data.isEmpty()) return@withContext null

        try {
            val folderPath = path.substring(0, path.lastIndexOf("/"))
            val folder = File(folderPath)
            if (!folder.exists()) folder.mkdirs()

            FileUtils.writeByteArrayToFile(File(path), data)
            return@withContext Uri.fromFile(File(path))
        } catch (e: Exception) {
            println(e.message)
        }
        return@withContext null
    }
}